﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebAppAuthAdmin.AuthApiManagementServiceReference;
using Web.Framework;
using WebAppAuthAdmin.Code;
using AuthApi.Contracts;
using WebAppAuthAdmin.Code.Security;
using AuthApi.Contracts.Search;

namespace WebAppAuthAdmin.App
{
    public partial class UserList : BasePage
    {
        private WebApplicationInfo applicationInfo
        {
            get
            {
                return (WebApplicationInfo)ViewState["webApplicationInfo"];
            }
            set
            {
                ViewState["webApplicationInfo"] = value;
            }
        }

        private List<LinkButton> actionButtons = new List<LinkButton>();
        LinkButton crearUsuariosButton = new LinkButton();
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);           
            
            crearUsuariosButton.ID = "crearUsuarios";
            crearUsuariosButton.Text = "Crear Usuario";
            crearUsuariosButton.Click += new EventHandler(lnkCrearUsuario_Click);
            actionButtons.Add(crearUsuariosButton);

            base.LoadContextActions(actionButtons);
        }

        protected override void ApplySecurity()
        {
            bool hasPermissionToEditUser = HasPermissionFor(AppSecurity.APP_VIEW_ALL_USERS);
            var company = this.GetSingleContextCompany();
            bool paginaInvalida = false;
            if (applicationInfo == null)
            {
                if (company.Id == 0)
                {
                    paginaInvalida = true;
                    this.masterPage.ShowMessage("No se puede buscar a los usuarios para todas las aplicaciones sin marca seleccionada. Acceda por la aplicación.", WebMessageType.Notification);
                }
                else
                {

                    HasPermissionToSeeMe(AppSecurity.APP_VIEW_ALL_USERS);
                    hasPermissionToEditUser = HasPermissionFor(AppSecurity.APP_VIEW_ALL_USERS);
                    this.lblApplication.Text = "Todas";
                    this.lnkCrearUsuario.Visible = false;
                    this.pnlUsuarioRegistrados.Visible = false;
                }
            }
            else
            {
                HasPermissionToSeeMe(AppSecurity.APP_VIEW_USERS_ID_ + applicationInfo.Id.ToString());
                hasPermissionToEditUser = HasPermissionFor(AppSecurity.APP_VIEW_USERS_ID_ + applicationInfo.Id.ToString());
                this.lblApplication.Text = applicationInfo.Name;
                this.lnkCrearUsuario.Visible = true;
            }

            this.lnkCrearUsuario.Visible = HasPermissionFor(AppSecurity.APP_USER_CREATE) && applicationInfo != null;
            actionButtons.Where(a => a.ID == "crearUsuarios").Single().Visible = this.lnkCrearUsuario.Visible;

            this.GridUsers.Columns[0].Visible = hasPermissionToEditUser;

            if (paginaInvalida)
            {
                this.GridUsers.Columns[0].Visible = false;
                this.lnkBuscar.Enabled = false;
                crearUsuariosButton.Visible = false;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                this.lnkBuscar.Attributes.Add("aspnetid", this.lnkBuscar.UniqueID);
                
                if (!this.IsPostBack)
                {
                    string appIdStr = this.Request.QueryString["applicationId"];

                    if (!String.IsNullOrEmpty(appIdStr))
                    {
                        int appId = Convert.ToInt32(appIdStr);
                        applicationInfo = WebServiceHelper.GetApplicationById(appId);

                        HasPermissionToSeeMe(AppSecurity.APP_VIEW_ALL_USERS, AppSecurity.APP_VIEW_USERS_ID_ + appId.ToString());
                    }
                    else
                    {
                        // Son todas las applicaciones
                        applicationInfo = null;
                        this.chkCondierarRegistrados.Checked = false;
                        HasPermissionToSeeMe(AppSecurity.APP_VIEW_ALL_USERS);
                    }

                    this.LoadCbos();
                }

                if (applicationInfo == null)
                {
                    HasPermissionToSeeMe(AppSecurity.APP_VIEW_ALL_USERS);
                }
                else
                {
                    HasPermissionToSeeMe(AppSecurity.APP_VIEW_ALL_USERS, AppSecurity.APP_VIEW_USERS_ID_ + applicationInfo.Id.ToString());
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
            
        }

        private void LoadCbos()
        {
            List<KeyValuePair<string, string>> estadosBloqueados = UIHelper.CreateThreeState("Bloqueados", "Activos (No bloqueados)");
            UIHelper.LoadCbo(estadosBloqueados, cboUsuariosBloqueados, "Todos", "Key", "Value");           
        }        

        private void Buscar()
        {
            SearchUser search = new SearchUser();
            search.CompanyId = this.GetSingleContextCompany().Id;
            search.NameLike = this.txtNombre.Text;
            //RegistradosParaLaAplicacion            

            search.Bloqueados = UIHelper.GetThreeStateFromValue(this.cboUsuariosBloqueados.SelectedValue);           
            search.ConsiderarRegistradosParaLaAplicacion = this.chkCondierarRegistrados.Checked;            
            
            if (applicationInfo == null)
            {               
                // Busco usuarios para todas las aplicaciones
                search.ApplicationId = 0;
                this.GridUsers.DataSource = WebServiceHelper.GetUsers(search);
                this.GridUsers.Columns[3].Visible = false;
            }
            else
            {
                // Busco usuarios para la aplicación de contexto
                search.ApplicationId = applicationInfo.Id;
                this.GridUsers.DataSource = WebServiceHelper.GetUsers(search);
            }

            this.GridUsers.DataBind();
            pnlResults.Visible = true;
        }

        protected void GridUsers_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "editar")
                {
                    if (applicationInfo == null)
                    {
                        string userName = Convert.ToString(this.GridUsers.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                        this.Response.Redirect(string.Format("/App/UserViewApplications.aspx?UserName={0}", userName), true);
                    }
                    else
                    {
                        string userName = Convert.ToString(this.GridUsers.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                        this.Response.Redirect(string.Format("/App/UserViewApplications.aspx?UserName={0}", userName), true);
                        //this.Response.Redirect(string.Format("/App/UserEdit.aspx?UserName={0}&Application={1}", userName, applicationInfo.Id), true);
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkBuscar_Click(object sender, EventArgs e)
        {
            try
            {
                Buscar();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkCrearUsuario_Click(object sender, EventArgs e)
        {
            try
            {
                if (applicationInfo != null)
                {
                    this.Response.Redirect(string.Format("/App/UserCreate.aspx?applicationId={0}", applicationInfo.Id), true);
                }
                else
                {
                    this.Response.Redirect("/App/UserCreate.aspx", true);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
    }
}